<template>
  <div class="search-wrap">
    <div class="common-search ym-box">
      <el-form :model="queryForm" inline size="small" @submit.prevent>
        <el-form-item>
          <el-input
            v-model="queryForm.name"
            placeholder="请输入科室/部门名称查询"
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item class="btn-search-item">
          <el-button type="primary" :disabled="did === ''" class="btn-search" @click="search"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <el-button v-if="did" type="primary" class="btn-add" size="small" @click="create"
        >创建科室/部门</el-button
      >
    </div>
  </div>

  <div class="table-wrap ym-box">
    <ym-table
      v-loading="state.tableLoading"
      :data="state.tableData"
      :column-data="depColumnData"
      :style="{ height: `${tableHeight}px` }"
      :height="tableHeight"
      element-loading-text
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <template #depName="{ row }">
        <div class="cell-name" @click="editInit(row)">{{ row.depName }}</div>
      </template>
      <template #status="{ row }">
        <el-switch
          v-model="row.status"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="changeStatus(row)"
        />
      </template>
      <template #contact="{ row }">
        <div class="contact-cell">
          <span class="contact">{{ row.contact }}</span>
          <span v-if="row.contactPhone" class="sperator">|</span>
          <span class="phone">{{ row.contactPhone }}</span>
        </div>
      </template>
      <template #operator="{ row }">
        <el-button type="text" size="small" class="btn-edit" @click="editInit(row)">修改</el-button>

        <el-button type="text" size="small" class="btn-del" @click="del(row)">删除</el-button>
      </template>
    </ym-table>

    <pagination
      id="page-block"
      v-model:page-num="state.pageObj.pageNum"
      v-model:page-size="state.pageObj.pageSize"
      :total="state.pageObj.total"
      @pagination="search"
    />
  </div>

  <!-- 创建或修改对话框 -->
  <drawer
    v-model:visible="state.dialogVisible"
    :size="500"
    :title="state.dialogTitle"
    @close="closeDrawer"
  >
    <add-or-edit-form
      ref="formWrapper"
      :form="_state.form"
      :is-add="state.isAdd"
      @cancel="handleClose"
      @confirm="confirm"
    />
  </drawer>
</template>

<script lang="ts" setup>
import { defineExpose, defineProps, reactive, ref, toRefs, watch } from 'vue'

import { ElMessage, ElMessageBox } from 'element-plus'

import AddOrEditForm from './Dep/AddOrEditForm.vue'

import DepApi from '@/api/backend/dep'

import { useTable } from '@/utils/common/useTable'
import { getStyle } from '@/utils/dom'
import { depColumnData } from '&/utils/columnData'

import { commonHandle } from '@/views/mixins/common'
import { Drawer, Pagination, YmTable } from '&/mixins/useComponent'
import IBaseObj from '#/index'

const { tableHeight } = useTable({
  root: '#dep-content .table-wrap',
  elements: ['#dep-content .page-block'],
  otherFunc: () => {
    const tablewrapPaddingTop = parseFloat(getStyle('#dep-content .table-wrap')?.paddingTop || 0)
    const tablewrapPaddingtBottom = parseFloat(
      getStyle('#dep-content .table-wrap')?.paddingBottom || 0
    )

    return tablewrapPaddingTop + tablewrapPaddingtBottom
  },
})

const { state, handleAdd, handleEdit, handleClose, handleSearch, handleDelete } = commonHandle()

const props = defineProps({
  did: {
    type: [String, Number],
    default: '',
  },
  oid: {
    type: [String, Number],
    default: '',
  },
})

watch(
  () => props.did,
  () => {
    search()
  }
)

const _state = reactive({
  queryForm: {
    name: '',
  },
  form: {
    oid: props.oid,
    upper: props.did,
    name: '',
    type: '',
    contact: '',
    contactPhone: '',
    remark: '',
    tier: 0,
    status: 1,
  },
})
const { queryForm } = toRefs(_state)

const search = () => {
  handleSearch(DepApi.getDepByPage, {
    ...queryForm.value,
    upper: props.did,
    oid: props.oid,
  })
}

const create = () => {
  handleAdd('创建科室部门')
}

const changeStatus = async (row: IBaseObj) => {
  let msg = ''
  let successMsg = ''
  if (!row.status) {
    msg = `确认禁用部门${row.name}`
    successMsg = '禁用成功'
  } else {
    msg = `确认启用部门${row.name}`
    successMsg = '启用成功'
  }

  ElMessageBox.confirm(msg, '系统提示', {
    showClose: false,
  })
    .then(async () => {
      const ret = await DepApi.updateStatus({
        did: row.did,
        status: row.status === 1 ? 0 : 1,
      })
      if (ret.data) {
        ElMessage({ message: successMsg })
        search()
      }
    })
    .catch(() => {
      row.status = row.status === 1 ? 0 : 1
    })
}

const editInit = async (row: IBaseObj) => {
  const ret = await DepApi.getDepById(row.did)
  if (ret.data) {
    handleEdit('修改科室部门')
    _state.form = ret.data
  }
}

const del = (row: IBaseObj) => {
  handleDelete({
    url: DepApi.delUrl,
    id: row.did,
    message: '此操作将永久删除该科室部门，是否继续?',
    success: () => {
      search()
    },
  })
}
const formWrapper = ref()
const addOrEditReset = () => {
  formWrapper.value.clear()
  _state.form = {
    oid: props.oid,
    upper: props.did,
    name: '',
    type: '',
    contact: '',
    contactPhone: '',
    remark: '',
    tier: 0,
    status: 1,
  }
}

const closeDrawer = () => {
  state.isAdd = true
  addOrEditReset()
}

const confirm = () => {
  handleClose()
  search()
}

defineExpose({
  search,
})
</script>

<style lang="scss" scoped>
.table-wrap {
  flex: 1;
}
</style>
